<template>
  <NavBar title="兑换记录" color="#fff" colorText="#333" brg="#f8f8f8">
  <view class="exchange-record-container">
    <!-- 主内容区域 -->
    <view class="content-area">
		<scroll-view
		  class="record-list-container"
		  scroll-y="true"
		  @scrolltolower="onScrollToLower"
		  lower-threshold="100"
		>
      <!-- 加载状态 -->
      <view class="loading-state" v-if="loading">
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 记录列表 -->
      <view class="record-list" v-else-if="exchangeRecords.length > 0">
        <view
          v-for="(record, index) in exchangeRecords"
          :key="record.id || index"
          class="record-item"
        >
          <view class="record-content">
            <view class="record-left">
              <text class="record-desc">{{ record.description }}</text>
              <text class="record-date">{{ record.date }}</text>
            </view>
            <view class="record-right">
              <text class="record-amount">{{ record.amount }}</text>
              <view class="status-container">
                <text class="status-text">{{ record.status }}</text>
                <image class="status-image" src="/static/statu.png" mode="widthFix"></image>
              </view>
            </view>
          </view>
          <view class="record-divider" v-if="index < exchangeRecords.length - 1"></view>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-else-if="!loading && exchangeRecords.length === 0">
        <image class="empty-icon" src="/static/empty.png" mode="widthFix"></image>
        <text class="empty-text">暂无兑换记录</text>
        <text class="empty-desc">快去完成任务赚取金豆吧</text>
      </view>
	  </scroll-view>
    </view>
  </view>
  </NavBar>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getToken, isLoggedIn } from '../../utils/user.js'
import { REDPACKET_API } from '../../config/api.js'

// 响应式数据
const exchangeRecords = ref([])
const loading = ref(false)
const error = ref('')
const currentPage = ref(1)

// 方法
const goBack = () => {
  uni.navigateBack()
}

// 页面加载时获取数据
onMounted(() => {
  // 这里可以调用API获取兑换记录
  loadExchangeRecords()
})

// 格式化时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''

  try {
    const date = new Date(dateTimeStr)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  } catch (error) {
    console.error('时间格式化失败:', error)
    return dateTimeStr
  }
}


// 滚动到底部加载更多
const onScrollToLower = () => {
  console.log('滚动到底部，检查是否需要加载更多数据')

  // 如果正在加载或没有更多数据，则不执行
  if (loading.value || !hasMore.value) {
    console.log('跳过加载：', { loading: loading.value, hasMore: hasMore.value })
    return
  }

  console.log('开始加载下一页数据，当前页：', currentPage.value)

  // 增加页码并加载下一页
  currentPage.value++
  fetchRecords(false)
}

const fetchRecords = () => {
  console.log('11')
}
// 加载兑换记录
const loadExchangeRecords = async () => {
  // 检查登录状态
  const loginStatus = isLoggedIn()
  if (!loginStatus) {
    console.log('用户未登录，不请求记录接口')
    exchangeRecords.value = []
    return
  }

  try {
    loading.value = true
    error.value = ''

    const token = getToken()
    if (!token) {
      throw new Error('未找到用户token，请重新登录')
    }

    const response = await uni.request({
      url: REDPACKET_API.LIST,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    })

    console.log('兑换记录API响应:', response)

    if (response.statusCode === 200 && response.data.code === 200) {
      const apiData = response.data.data || {}
      const recordList = apiData.list || []

      // 转换API数据为页面需要的格式
      exchangeRecords.value = recordList.map(record => ({
        id: record.id,
        description: '兑换红包，红包拿来！', // 固定标题
        date: formatDateTime(record.created_at), // 格式化时间
        amount: `${record.red_packet} 元`, // 金额和元之间加空格
        status: record.status_text, // 状态文本
        orderNo: record.order_no,
        withdrawBeans: record.withdraw_beans
      }))

      console.log('转换后的兑换记录:', exchangeRecords.value)
    } else {
      throw new Error(response.data?.message || '获取兑换记录失败')
    }

  } catch (err) {
    console.error('获取兑换记录失败:', err)
    error.value = err.message || '获取记录失败，请重试'
    uni.showToast({
      title: error.value,
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.exchange-record-container {
  min-height: 100vh;
  background: linear-gradient( 180deg, #C2DDFF 0%, #FFFFFF 100%);
  border-radius: 0rpx 0rpx 0rpx 0rpx;
  position: relative;
  padding-top: 160rpx;
}
/* 记录列表容器 */
.record-list-container {
  height: calc(100vh - 200rpx);
  margin: 0 30rpx;
  background: #FFFFFF;
  border-radius: 20rpx 20rpx 20rpx 20rpx;
  width: 92%;
}
/* 状态栏 */
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 40rpx 10rpx;
  background: transparent;
}

.status-time {
  font-size: 34rpx;
  font-weight: 600;
  color: #000;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.status-icons {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.status-icon {
  font-size: 24rpx;
  color: #000;
}

/* 导航栏 */
.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 40rpx;
  background: #E3F2FD;
}

.back-button {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 30rpx;
  background: rgba(255, 255, 255, 0.2);
}

.back-icon {
  font-size: 32rpx;
  color: #666;
  font-weight: bold;
}

.nav-title {
  font-size: 36rpx;
  font-weight: 700;
  color: #000;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.nav-placeholder {
  width: 60rpx;
  height: 60rpx;
}

/* 主内容区域 */
.content-area {
  flex: 1;
  padding: 30rpx 20rpx;
}

.record-list {
  background: white;
  overflow: hidden;
  width: 95%;
  margin: 10rpx auto 0;
  border-bottom: 2rpx dashed #8B8B8B;
  }

.record-item {
  position: relative;
}

.record-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 25rpx;
}

.record-left {
  flex: 1;
  margin-right: 20rpx;
}

.record-desc {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
  display: block;
  margin-bottom: 18rpx;
  line-height: 1.4;
}

.record-date {
  font-size: 24rpx;
  color: #999;
  display: block;
}

.record-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 12rpx;
}

.record-amount {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-left: 50rpx;
  text-align: center;
}

.status-container {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 50rpx;
}

.status-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 22rpx;
  color: #BFBFBF;
  font-weight: 500;
  z-index: 2;
  white-space: nowrap;
}

.status-image {
  width: 98rpx;
  height: 38rpx;
  z-index: 1;
}







/* 分割线 */
.record-divider {
  height: 1rpx;
  background: repeating-linear-gradient(
    to right,
    #8B8B8B  0rpx,
    #8B8B8B  8rpx,
    transparent 8rpx,
    transparent 16rpx
  );
  margin: 0 30rpx;
}

/* 加载状态 */
.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 120rpx 40rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 40rpx;
  text-align: center;
}

.empty-icon {
  width: 146rpx;
  height: 200rpx;
  margin-top: 250rpx;
}

.empty-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #666;
  margin-bottom: 16rpx;
}

.empty-desc {
  font-size: 24rpx;
  color: #999;
  line-height: 1.4;
  margin-bottom: 30rpx;
}

.retry-btn {
  font-size: 26rpx;
  color: #8B5CF6;
  padding: 10rpx 20rpx;
  border: 1rpx solid #8B5CF6;
  border-radius: 20rpx;
  cursor: pointer;
}

.retry-btn:active {
  opacity: 0.7;
}

/* 响应式适配 */
@media screen and (max-width: 750rpx) {
  .record-content {
    padding: 24rpx;
  }
  
  .record-desc {
    font-size: 26rpx;
  }
  
  .record-amount {
    font-size: 28rpx;
  }
}

/* 安全区域适配 */
@supports (padding: max(0px)) {
  .exchange-record-container {
    padding-bottom: max(0px, env(safe-area-inset-bottom));
  }
}
</style>
